package com.yunda.nebula.gateway.sync.http;

import com.yunda.nebula.gateway.core.enums.DataEventTypeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * \* User: wei.zhang
 * \* Date: 2020/9/17 11:34
 * \* Description:
 *
 * @author wei.zhang
 * \
 */
@Data
@Slf4j
public class AppRefreshTask implements Runnable,HttpTask{

    private AtomicBoolean RUNNING = new AtomicBoolean(true);
    private HttpSyncDataService syncDataService;

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
        }
        while (RUNNING.get()){
            try {
                List<String> apps = syncDataService.fetchAllApps();
                for (String app:apps){
                    if (!syncDataService.getAppIds().contains(app)){
                        log.info("定时任务获取到新的任务，加入线程池中!!!appid 为 {}",app);
                        syncDataService.getAppIds().add(app);
                        syncDataService.doFetchAppConfig(app, DataEventTypeEnum.CREATE);
                        syncDataService.createTask(app);
                    }
                }
                TimeUnit.SECONDS.sleep(10);
            }catch (Exception e){
                log.error("获取appid任务 出错，",e);
            }
        }
        log.info("stop AppRefreshTask task！！！");
    }

    @Override
    public void stop() {
        RUNNING.compareAndSet(true,false);
    }
}
